package org.skydiveapplibrary.ui;

import java.util.ArrayList;

import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

public class ViewPagerAdapter extends PagerAdapter
	implements ViewPager.OnPageChangeListener {
    private static final String TAG = "ViewPagerAdapter";
    private static final boolean DEBUG = false;

	private final ViewPager mViewPager;
	private final FragmentManager mFragmentManager;
	private final static ArrayList<FragInfo> mFrags = new ArrayList<FragInfo>();
	private boolean showMenus = true;

    private FragmentTransaction mCurTransaction = null;
    private Fragment mCurrentPrimaryItem = null;
	
	static final class FragInfo
	{
		private final Fragment fragment;
		private final Bundle args;
		
		FragInfo(Fragment _fragment, Bundle _args)
		{
			fragment = _fragment;
			args = _args;
		}
	}
	
	public ViewPagerAdapter(FragmentActivity activity, ViewPager pager)
	{
		mFragmentManager = activity.getSupportFragmentManager();
		mViewPager = pager;
		mViewPager.setAdapter(this);
		mViewPager.setOnPageChangeListener(this);
		this.Clear();
	}
	
	public void addFrag(Fragment fragment, Bundle args)
	{
		FragInfo info = new FragInfo(fragment, args);
		mFrags.add(info);
		notifyDataSetChanged();
	}

	@Override
	public int getCount()
	{
		return mFrags.size();
	}
	
	public Fragment getItem(int position)
	{
		FragInfo info = mFrags.get(position);
		return info.fragment;
	}
	
	@Override
	public String getPageTitle(int position)
	{
		String returnValue = mFrags.get(position).args.getString("Title");
		if (returnValue == null)
			return "";
		else
			return returnValue;
	}
	
	public void showMenus(Boolean mShowMenus)
	{
		showMenus = mShowMenus;
  	
	  	Fragment fragment = mFragmentManager.findFragmentByTag(makeFragmentName(mViewPager.getId(), mViewPager.getCurrentItem()));
	  	
	  	if (fragment != null)
	  	{
	  		fragment.setMenuVisibility(showMenus);
	  		fragment.setUserVisibleHint(showMenus);
	  	}
	}
  
	public String getTag(int position)
	{
		String returnValue = mFrags.get(position).args.getString("Tag");
		if (returnValue == null)
			return "";
		else
			return returnValue;
	}
	
	public void Clear()
	{
		mFrags.clear();
	}
	
	@Override
	public void onPageScrollStateChanged(int arg0)
	{
		// TODO Auto-generated method stub
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2)
	{
		// TODO Auto-generated method stub
	}

	@Override
	public void onPageSelected(int arg0)
	{
		// TODO Auto-generated method stub
	}

	//////////////////////////////////////////////////////////
	// Copied from FragmentPagerAdapter v6 December Release //
	//////////////////////////////////////////////////////////
	
    @Override
    public void startUpdate(ViewGroup container)
    {
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position)
    {
    	if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }

        // Do we already have this fragment?
        String name = makeFragmentName(container.getId(), position);
        Fragment fragment = mFragmentManager.findFragmentByTag(name);
        if (fragment != null) {
            if (DEBUG) Log.v(TAG, "Attaching item #" + position + ": f=" + fragment);
            mCurTransaction.attach(fragment);
        } else {
            fragment = getItem(position);
            if (DEBUG) Log.v(TAG, "Adding item #" + position + ": f=" + fragment);
            mCurTransaction.add(container.getId(), fragment,
                    makeFragmentName(container.getId(), position));
        }
        if (fragment != mCurrentPrimaryItem) {
            fragment.setMenuVisibility(false);
            fragment.setUserVisibleHint(false);
        }

        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object)
    {
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }
        if (DEBUG) Log.v(TAG, "Detaching item #" + position + ": f=" + object
                + " v=" + ((Fragment)object).getView());
        mCurTransaction.detach((Fragment)object);
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object)
    {
        Fragment fragment = (Fragment)object;
        if (fragment != mCurrentPrimaryItem) {
            if (mCurrentPrimaryItem != null) {
                mCurrentPrimaryItem.setMenuVisibility(false);
                mCurrentPrimaryItem.setUserVisibleHint(false);
            }
            if (fragment != null) {
                fragment.setMenuVisibility(showMenus);
                fragment.setUserVisibleHint(showMenus);
            }
            mCurrentPrimaryItem = fragment;
        }
    }

    @Override
    public void finishUpdate(ViewGroup container)
    {
        if (mCurTransaction != null) {
            mCurTransaction.commitAllowingStateLoss();
            mCurTransaction = null;
            mFragmentManager.executePendingTransactions();
        }
    }

    @Override
    public boolean isViewFromObject(View view, Object object)
    {
        return ((Fragment)object).getView() == view;
    }

    @Override
    public Parcelable saveState()
    {
        return null;
    }
    
    @Override
    public void restoreState(Parcelable state, ClassLoader loader)
    {
    }

    private String makeFragmentName(int viewId, int position)
    {
    	// added so fragments can be given unique tags
    	String name = getTag(position);
    	if (name != null && name.equals("") == false)
    		return name;
    	else
    		return "android:switcher:" + viewId + ":" + position;
    }
}
